package com.example.demo.controller;

import com.example.demo.loader.MemoryClassLoader;
import com.example.demo.utils.BaseUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/exec")
public class CompileController {

	@PostMapping("/JavaCompile")
	public Map<String, Object> exec(String code) {
		Map<String, Object> r = new HashMap<>(8);
		String fullName;
		r.put("code", 500);
		r.put("result", "代码错误");
		if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(fullName = BaseUtil.getFullName(code))) {
			try {
				String javaCode = BaseUtil.getJavaCode(code);
				MemoryClassLoader loader = MemoryClassLoader.genInstance();
				loader.registerJava(fullName, javaCode);
				Class<?> clazz = loader.getClass(fullName);
				if (clazz != null) {
					Object instance = clazz.newInstance();
					Method mt = clazz.getDeclaredMethod("main", String[].class);
					ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
					PrintStream ps = new PrintStream(bos);
					System.setOut(ps);
					mt.invoke(instance, (Object) new String[]{});
					String msg = bos.toString();
					r.put("code", 200);
					r.put("result", msg);
				}
			} catch (Exception e) {
				e.getStackTrace();
			}
		}
		return r;
	}
}
